Skip to content

fix(serve): serve the current graph while graph.json reloads (#5371) - #5374

Closed
Deepjyoti-Sarmah wants to merge 3 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/5371-serve-reload-off-loop
Closed

Deepjyoti-Sarmah wants to merge 3 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/5371-serve-reload-off-loop

Conversation

@Deepjyoti-Sarmah

@Deepjyoti-Sarmah Deepjyoti-Sarmah commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #5371. While graph.json reloads, MCP requests no longer wait for it. They are answered from the graph already in memory. Only the request that triggered the reload waits.

#5181 (for #5177) already made _GraphContextCache.load() return the stale entry to a second caller while a rebuild is in flight. That branch could never run in the server. call_tool and read_resource are coroutines that call _select_graph() → load() → _load_entry() (parse + trigram index) synchronously on the event loop. Nothing else is dispatched until the load returns, so there is never a second caller.

v8                                          this PR
call_tool                                   call_tool
  _select_graph()  ── load on the loop ──     await to_thread(_load_ctx)   ── load in a worker
  handler()                                   _select_graph()   (cache hit, or the current entry)
                                              handler()         (no await after the bind)

The new _warm_graph() runs only the load in a worker thread. G is still bound synchronously right before the handler, with no await in between, so another call cannot swap the shared G in the middle of a handler.

I also tried running _select_graph itself in the thread. It passes the new tests but answers from the wrong graph: 5 of 40 calls in a two-project race probe. It rebinds G across an await, so another call can swap it before the handler runs. This PR got 0 of 40 in the same probe.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Tests or CI
  • Refactor
  • Security fix

Verification & Invariants

Invariant: a request that arrives while a graph reloads is answered from that graph's current entry without waiting, and the handler always sees the graph its own request selected.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added a regression test (if bug fix) or isolated boundary test.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly.

Merge Danger

Door: two-way. Reverting 58a7339 restores v8's behaviour.

Blast Radius: small.

  • It only affects call_tool and read_resource in graphify/serve.py, for stdio and HTTP alike.
  • There is no output change and no cache schema change.
  • anyio is already an mcp dependency.

Limitations

  • The worker thread still holds the GIL while it parses JSON and builds the trigram index. So concurrent requests are served during a reload, but more slowly than when warm (see the numbers below). A process-level loader would be a larger change.
  • The first ever load of a path (nothing stale to serve) still waits, as before.

How was this tested?

There's a new file, tests/test_serve_reload_off_loop.py. It drives the server's own MCP request handlers concurrently, with _load_entry slowed to 0.8 s. Each request is timed from its planned arrival time: timing from when the coroutine starts would hide the stall.

test_concurrent_tool_calls_served_from_current_graph_during_reload   3 graph_stats during a reload
test_resource_read_not_blocked_by_a_tool_call_reload                 resources/read during a reload
test_project_call_during_default_reload_answers_its_own_graph       project_path call: right graph, fast
tree new tests
v8 b582ad4 3 failed (each waits ~0.76 s)
58a7339 3 passed

Here is an end-to-end run with the issue's stdio harness (from #5177) on a generated 80k-node / 160k-edge graph (22 MB). It sends 3 graph_stats calls 0.2 s apart, right after touch graph.json:

tree warm after rewrite
v8 0.40 s 6.75 / 6.93 / 6.73 s
this PR 0.56 s 7.31 / 1.35 / 2.22 s

I ran the full suite for v8 and this branch at the same time in the same venv:

tree failed passed
v8 b582ad4 0 11760
58a7339 0 11763

ruff check graphify/serve.py tests/test_serve_reload_off_loop.py -> All checks passed!

The new tests also fail on v8's serve.py and pass with the fix under mcp 2.3.0, the version CI uses: the helper dispatches through get_request_handler() there and request_handlers on 1.x.

Not tested: Windows.

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. (N/A: no skill fragments touched.)
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables). (Extraction not touched.)
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python).
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages. (No trailer in the commit messages.)

Drive the server's own request handlers concurrently with a slow
_load_entry. On v8 every request waits out the reload, because call_tool
and read_resource load the graph on the event loop.
…urce

call_tool and read_resource called _select_graph() -> _ctx_cache.load()
synchronously on the event loop. A reload of a large graph.json stopped
every other request, so the stale entry Graphify-Labs#5181 hands concurrent callers
was never reachable (Graphify-Labs#5371).

Run the load in a worker thread first, then bind G with the synchronous
_select_graph, which is now a cache hit or the current entry. The handler
still runs with no await after the bind, so another call cannot swap G
mid-handler.
@github-actions github-actions Bot added the contributor Pull request from a returning community contributor label Nov 21, 2026
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @Deepjyoti-Sarmah. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.11 and 3.13, and that the change keeps extraction deterministic.

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify code review View in Graphify

Review completed · 8bbc794bf70a

Note

Merge confidence: 5/5 · Nothing blocking · 4 possible issues to check · 🟠 High impact
4 possible issues not confirmed
7 not re-checked

Tool calls and resource reads now load or reload their graph in a worker thread before selecting the graph for the request.

Full summary

Tool calls and resource reads now load or reload their graph in a worker thread before selecting the graph for the request. The request handler still runs synchronously after graph selection.

No confirmed issues. We found 4 possible issues we couldn't confirm; see below.

Not confirmed (4 possible issues)

Leads worth a look; we didn't double-check these. They don't change the score.

Not confirmed · The project-call timing test can pass without slowing the reload when the graph path does not match the substring filter Inspect source

Detailed review · not confirmed

The slow-load filter matches slow_only as a substring of the resolved path. If the resolved path is spelled differently from tmp_path (for example through a symlink), the filter never matches, no load is slowed, and the test passes without checking the behavior it is meant to guard.

slow at line 33 only sleeps when slow_only in resolved_path, and line 104 passes str(tmp_path / "graph.json") unnormalized. The test then asserts only that the project call took less than DELAY/2 at line 121 and never checks that the default reload took DELAY, so a non-match leaves nothing to fail.

  • Not checked whether tmp_path is already resolved on the test platform

  • Not checked how _load_entry formats resolved_path

  • Found by the per-file sweep; not double-checked.

Not confirmed · The concurrent tool-call test is named for serving the current graph but never checks the returned content Inspect source

Detailed review · not confirmed

The test named for serving the current graph during a reload asserts only timing. It never checks which graph text the non-triggering calls returned.

Line 86 discards the response text returned by _send, and line 88 asserts only on times. The test would not catch a regression that returns the wrong graph quickly, even though the title and the module docstring say the calls are answered from the current graph.

  • Not checked what graph_stats returns for GRAPH with one node

  • Timing thresholds of DELAY/2 may be flaky on a heavily loaded CI host

  • Found by the per-file sweep; not double-checked.

Not confirmed · Project graph can be evicted during the background load, so the event loop still rebuilds it and stalls other requests Inspect source

Detailed review · not confirmed

The _warm_graph offload only helps if the graph is still cached when _select_graph runs. Other requests can run during the await and load other project graphs, evicting this one from the bounded LRU. Then _select_graph rebuilds the graph synchronously on the event loop, which is the stall #​5371 was meant to remove.

_warm_graph at line 2989 only calls _load_ctx and discards the result. _select_graph at line 3535 (and at line 2970 and line 3477) then calls _load_ctx again on the loop thread, without any await in between. The docstring at lines 2980-2981 assumes _select_graph is always a cache hit or sees an in-flight entry, but nothing guarantees the entry survives the await. The LRU bound comes from _max_server_contexts(), which is not shown.

  • The eviction policy and capacity of _GraphContextCache and the value returned by _max_server_contexts() are not in the inspected range.

  • Whether _ctx_cache.load rebuilds or blocks on a stale entry is not shown.

  • Found by the per-file sweep; not double-checked.

Not confirmed · Graph cache is now loaded from several worker threads at once, so it can race and rebuild the same graph repeatedly Inspect source

Detailed review · not confirmed

Before this change every load ran on the event loop, so calls were serialized. Now _warm_graph runs _load_ctx in worker threads, so concurrent calls can enter the cache at the same time. Concurrent loads of the same stale graph can each rebuild it, and the cache's internal bookkeeping may be unsafe under concurrent access.

anyio.to_thread.run_sync(_load_ctx, ...) at line 2989 has no per-path coalescing or lock. The comment at lines 2953-2957 says the event loop serialized access to the shared context, which no longer holds for the load. The cache's locking is not in the inspected range.

  • The _GraphContextCache implementation is not in the inspected range, so whether it uses a lock or single-flight loading is unknown.

  • Actual interleaving depends on the anyio worker thread limit, which is not shown.

  • Found by the per-file sweep; not double-checked.

What this review covered
  • Some lookups asked for files or lines that do not exist; the review was told and carried on.
  • 2 of 2 changed files inspected. This is scope, not a correctness guarantee.
Code graph and static checks · 881 functions depend on this change

Impact & health

Impact — 881 functions depend on the 226 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: _build_server() — 3 callers, 22 callees
  • worse: read_resource() — 1 callers, 8 callees

Formal checks — 881 functions this change can affect weren't formally checked in this review. Formal checks are informational only.

Gate & verification

✅ PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 650 function(s) in the blast radius were not formally verified this run

Test selection

29 of 608 test file(s) selected (5%) via static blast radius.

  • tests/test_4874_jvm_resolution.py — impact
  • tests/test_affected_cli.py — impact
  • tests/test_affected_path_file_node.py — impact
  • tests/test_affected_seed_reference_forms.py — impact
  • tests/test_benchmark.py — impact
  • tests/test_benchmark_raw_graph.py — impact
  • tests/test_benchmark_real_query.py — impact
  • tests/test_confidence_score_output.py — impact
  • tests/test_edge_also_seen.py — impact
  • tests/test_explain_same_file_tie.py — impact
  • tests/test_extract.py — impact
  • tests/test_file_label_disambiguation.py — impact
  • tests/test_graph_context_cache_reload.py — impact
  • tests/test_markdown_sections.py — impact
  • tests/test_mcp_graph_view_cache.py — impact
  • tests/test_path_cli.py — impact
  • tests/test_path_confidence.py — impact
  • tests/test_path_type_member.py — impact
  • tests/test_query_induced_edges.py — impact
  • tests/test_query_mcp_direction.py — impact
  • tests/test_query_names_its_graph.py — impact
  • tests/test_query_seed_order.py — impact
  • tests/test_query_seeds.py — impact
  • tests/test_query_source_first.py — impact
  • tests/test_serve.py — impact
  • tests/test_serve_http.py — impact
  • tests/test_serve_reload_off_loop.py — impact, changed-test
  • tests/test_terraform.py — impact
  • tests/test_truncation_full_answer.py — impact

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Docs that may be stale (advisory)

…and 10 more.

Every flagged function

  • _build_server() in graphify/serve.py:2906 · 3 callers, 22 callees: fans out to 22 callees (efferent coupling)
  • read_resource() in graphify/serve.py:3475 · 1 callers, 8 callees: fans out to 8 callees (efferent coupling)

CI runs mcp 2.x, whose Server has no public request_handlers. Look the
handler up with get_request_handler() there, and keep request_handlers
on 1.x.
safishamsi added a commit that referenced this pull request Nov 23, 2026
Maintainer tweaks on top of the #5299/#5394/#5315/#5374 batch:
- Move `import anyio` in serve.py to module top (was re-imported per call
  inside _warm_graph), a trivial cleanup on #5374.
- 0.9.117 changelog and version bump. No AST-cache schema change in this
  batch (query scoring, export filenames, serve reload, rcfile parsing).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@safishamsi

Copy link
Copy Markdown
Member

Landed in v0.9.118 via an authorship-preserving cherry-pick. The MCP server now loads graph.json off the event loop, so a large reload no longer blocks concurrent requests; a request during a reload is served the current graph and a corrupt reload leaves the old graph intact. One tiny maintainer cleanup: hoisted the anyio import to module top. Thanks @Deepjyoti-Sarmah!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor Pull request from a returning community contributor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

serve: graph reload still blocks every request (0.9.114)

2 participants